package com.ck.GUI;

/**
 * Created by ck on 2016/12/19.
 */
        import com.blacamdk.ChatNetModule.ClientMain;
        import com.blacamdk.ChatNetModule.User;
        import com.blacamdk.ChatNetModule.Utils;
        import com.blacamdk.ChatNetModule.syncWithServer;

        import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
        import java.awt.event.KeyAdapter;
        import java.awt.event.KeyEvent;
        import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.*;
        import javax.swing.border.Border;
        import javax.swing.event.ListSelectionEvent;
        import javax.swing.event.ListSelectionListener;

/**
 * 聊天窗体
 */
public class ChatFrame extends JFrame {
    private static final long serialVersionUID = -2310785591507878535L;
    /**
     * 聊天对方的信息Label
     */
    private JLabel otherInfoLbl;
    /**
     * 当前用户信息Lbl
     */
    private JLabel currentUserLbl;
    /**
     * 聊天信息列表区域
     */
    public static JTextArea msgListArea;
    /**
     * 要发送的信息区域
     */
    public static JTextArea sendArea;
    /**
     * 在线用户列表
     */
    public static int UIDTalking;//正在聊天的人
    public static String usernameTalking;//正在聊天的人
    public static JTextArea mainArea;
    public static DefaultListModel<String> onLineListModel;
    public static JList onlineList;
    public static JScrollPane infoPanel;
    /**
     * 在线用户数统计Lbl
     */
    public static JLabel onlineCountLbl;
    /** 准备发送的文件 */
    // public static FileInfo sendFile;

    /**
     * 私聊复选框
     */
    //public JCheckBox rybqBtn;

    public ChatFrame(String username) {
        this.init(username);
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        this.setVisible(true);
        //0.0
    }

    public void init(String username) {
        onLineListModel = new DefaultListModel<>();
        onlineList = new JList();
//        String imagePath = "images/Chat.png";// 构造图片的路径
//        Image imageIcon = Toolkit.getDefaultToolkit().getImage(getClass().getClassLoader().getResource(imagePath));// 这种写法就可以解决导出的Jar包也能显示图标了
//        setIconImage(imageIcon);
//        // setIconImage(Toolkit.getDefaultToolkit().getImage("images/123.png") );
        String imagePath = "/Chat.png";// 构造图片的路径
        try {
            Image img = ImageIO.read(this.getClass().getResource(imagePath));
            this.setIconImage(img);
        } catch (IOException e) {
            e.printStackTrace();
        }
        this.setTitle("聊天室");
        this.setSize(550, 500);
        this.setResizable(false);

        // 设置默认窗体在屏幕中央
        int x = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
        int y = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();
        this.setLocation((x - this.getWidth()) / 2, (y - this.getHeight()) / 2);

        // 左边主面板
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());
        // 右边用户面板
        JPanel userPanel = new JPanel();
        userPanel.setLayout(new BorderLayout());

        // 创建一个分隔窗格
        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, mainPanel, userPanel);
        splitPane.setDividerLocation(380);
        splitPane.setDividerSize(10);
        splitPane.setOneTouchExpandable(true);
        this.add(splitPane, BorderLayout.CENTER);

        // 左上边信息显示面板
//        JPanel infoPanel = new JPanel();
//        infoPanel.setLayout(new BorderLayout());
        mainArea=new JTextArea();
        mainArea.setEnabled(false);
        infoPanel=new JScrollPane(mainArea);
        infoPanel.setBorder(BorderFactory.createTitledBorder("欢迎使用!"));

        // 右下连发送消息面板
        JPanel sendPanel = new JPanel();
        sendPanel.setLayout(new BorderLayout());

        // 创建一个分隔窗格
        JSplitPane splitPane2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, infoPanel, sendPanel);
        splitPane2.setDividerLocation(300);
        splitPane2.setDividerSize(1);
        mainPanel.add(splitPane2, BorderLayout.CENTER);

//        otherInfoLbl = new JLabel("当前状态：群聊中...");
//        infoPanel.add(otherInfoLbl, BorderLayout.NORTH);

        msgListArea = new JTextArea();
        msgListArea.setLineWrap(true);
        infoPanel.add(new JScrollPane(msgListArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));

        JPanel tempPanel = new JPanel();
        tempPanel.setLayout(new BorderLayout());
        sendPanel.add(tempPanel, BorderLayout.NORTH);

        // 聊天按钮面板
        JPanel btnPanel = new JPanel();
        btnPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        tempPanel.add(btnPanel, BorderLayout.CENTER);

        // 字体按钮
        URL url = ChatFrame.class.getResource("/font.png");
        ImageIcon icon = new ImageIcon(url);
        JButton fontBtn = new JButton(icon);
        fontBtn.setMargin(new Insets(0, 0, 0, 0));
        fontBtn.setToolTipText("设置字体和格式");
        btnPanel.add(fontBtn);

        // 表情按钮
        //JButton faceBtn = new JButton(Toolkit.getDefaultToolkit().getImage(getClass().getClassLoader().getResource("images/sendFace.png")));
        URL url1 = ChatFrame.class.getResource("/sendFace.png");
        ImageIcon icon1 = new ImageIcon(url1);
        //ImageIcon icon1 = new ImageIcon("/sendFace.png");
        JButton faceBtn = new JButton(icon1);
        faceBtn.setMargin(new Insets(0, 0, 0, 0));
        faceBtn.setToolTipText("选择表情");
        btnPanel.add(faceBtn);

        // 发送文件按钮
        URL url2 = ChatFrame.class.getResource("/shake.png");
        ImageIcon icon2 = new ImageIcon(url2);
        JButton shakeBtn = new JButton(icon2);
        shakeBtn.setMargin(new Insets(0, 0, 0, 0));
        shakeBtn.setToolTipText("向对方发送窗口振动");
        btnPanel.add(shakeBtn);

        // 发送文件按钮
        URL url3 = ChatFrame.class.getResource("/sendPic.png");
        ImageIcon icon3 = new ImageIcon(url3);
        JButton sendFileBtn = new JButton(icon3);
        sendFileBtn.setMargin(new Insets(0, 0, 0, 0));
        sendFileBtn.setToolTipText("向对方发送文件");
        btnPanel.add(sendFileBtn);

        // 私聊按钮
        //rybqBtn = new JCheckBox("私聊");
        //tempPanel.add(rybqBtn, BorderLayout.EAST);

        // 要发送的信息的区域
        sendArea = new JTextArea();
        sendArea.setLineWrap(true);
        sendPanel.add(new JScrollPane(sendArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));

        // 聊天按钮面板
        JPanel btn2Panel = new JPanel();
        btn2Panel.setLayout(new FlowLayout(FlowLayout.RIGHT));
        this.add(btn2Panel, BorderLayout.SOUTH);
        JButton closeBtn = new JButton("注销");
        closeBtn.setToolTipText("退出整个程序");
        btn2Panel.add(closeBtn);
        JButton submitBtn = new JButton("发送");
        submitBtn.setToolTipText("按Enter键发送消息");
        btn2Panel.add(submitBtn);
        sendPanel.add(btn2Panel, BorderLayout.SOUTH);

        // 在线用户列表面板
        JPanel onlineListPane = new JPanel();
        onlineListPane.setLayout(new BorderLayout());

        // 添加到在线用户列表面板
        onlineCountLbl = new JLabel("在线用户列表(1)");
      //  onlineCountLbl.setMinimumSize(new Dimension(this.getWidth(), this.getHeight()));
        onlineListPane.add(onlineCountLbl, BorderLayout.NORTH);
        JScrollPane PaneFriend = new JScrollPane(onlineList);
        PaneFriend.setPreferredSize(new Dimension(200,400));
      //  onlineListPane.add(PaneFriend, BorderLayout.SOUTH);
        //PaneFriend.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        //PaneFriend.add(onlineList);
       // PaneFriend.getViewport().add(onlineCountLbl, BorderLayout.NORTH);
       // PaneFriend.setMinimumSize(new Dimension(this.getWidth(), this.getHeight()));
       // onlineCountLbl.setMinimumSize(new Dimension(this.getWidth(), this.getHeight()));
        // 当前用户面板
        JPanel currentUserPane = new JPanel();
        currentUserPane.setLayout(new BorderLayout());
        currentUserPane.add(new JLabel("当前用户:" + username), BorderLayout.NORTH);
//
        JSplitPane splistPane4=new JSplitPane(JSplitPane.VERTICAL_SPLIT,onlineListPane,PaneFriend);
        splistPane4.setDividerLocation(0.8);
        splistPane4.setDividerSize(5);

        // 右边用户列表创建一个分隔窗格
        JSplitPane splitPane3 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, splistPane4, currentUserPane);
        splitPane3.setDividerLocation(300);
        splitPane3.setDividerSize(20);
        userPanel.add(splitPane3, BorderLayout.CENTER);
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                // logout();
                closeBtn.doClick();
            }
        });

        onlineList.addListSelectionListener(listSelectionEvent -> {
            usernameTalking = (String)((JList)(listSelectionEvent.getSource())).getSelectedValue();
            int i;
            if((i = ClientMain.getIndexFromUsername(usernameTalking)) < 0)
                return;
            User u = ClientMain.userVector.get(i);
            UIDTalking = u.getUID();
            mainArea.setText("");
            mainArea.append(u.Content);
            infoPanel.setBorder(BorderFactory.createTitledBorder("正在与" + usernameTalking + "聊天"));
            //Main.cf.repaint();
        });
        //关闭按钮的事件
        closeBtn.addActionListener(event -> {
            //    logout();
            syncWithServer.flag = false;
            ClientMain.logout();
            System.exit(0);
        });

//        //选择某个用户私聊
//        rybqBtn.addActionListener(new ActionListener(){
//            public void actionPerformed(ActionEvent e) {
//                if(rybqBtn.isSelected()){
//                    User selectedUser = (User)onlineList.getSelectedValue();
//                    if(null == selectedUser){
//                        otherInfoLbl.setText("当前状态：私聊(选中在线用户列表中某个用户进行私聊)...");
//                    }else if(DataBuffer.currentUser.getId() == selectedUser.getId()){
//                        otherInfoLbl.setText("当前状态：想自言自语?...系统不允许");
//                    }else{
//                        otherInfoLbl.setText("当前状态：与 "+ selectedUser.getNickname()
//                                +"(" + selectedUser.getId() + ") 私聊中...");
//                    }
//                }else{
//                    otherInfoLbl.setText("当前状态：群聊...");
//                }
//            }
//        });
////        //选择某个用户
//        onlineList.addMouseListener(new MouseAdapter() {
//            public void mouseClicked(MouseEvent e) {
//                User selectedUser = (User)onlineList.getSelectedValue();
//                if(rybqBtn.isSelected()){
//                    if(DataBuffer.currentUser.getId() == selectedUser.getId()){
//                        otherInfoLbl.setText("当前状态：想自言自语?...系统不允许");
//                    }else{
//                        otherInfoLbl.setText("当前状态：与 "+ selectedUser.getNickname()
//                                +"(" + selectedUser.getId() + ") 私聊中...");
//                    }
//                }
//            }
//        });

        //发送文本消息
        sendArea.addKeyListener(new KeyAdapter(){
            public void keyPressed(KeyEvent e){
                if(e.getKeyCode() == Event.ENTER){
                    //ClientMain.sendTO(,);
                    submitBtn.doClick();
                }
            }
        });
        submitBtn.addActionListener(event -> {
            //sendTxtMsg();
            new Thread(() -> {
                long sendTime = ClientMain.sendTo(ClientMain.userVector.get(ClientMain.getIndexFromUsername(usernameTalking)).getUID(), sendArea.getText());
                if(sendTime < 0)
                    return;
                Utils.addContent(UIDTalking, sendTime, sendArea.getText(), true);
                if(sendTime < 0)
                    JOptionPane.showMessageDialog(ChatFrame.this, "发送失败");
                else
                    sendArea.setText("");
                mainArea.setText("");
                mainArea.append(ClientMain.userVector.get(ClientMain.getIndexFromUsername(usernameTalking)).Content);

                //mainArea.paintImmediately(mainArea.getBounds());
            }).start();
        });

//        //发送振动
//        shakeBtn.addActionListener(new ActionListener() {
//            public void actionPerformed(ActionEvent event) {
//                sendShakeMsg();
//            }
//        });
//
//        //发送文件
//        sendFileBtn.addActionListener(new ActionListener() {
//            public void actionPerformed(ActionEvent event) {
//                sendFile();
//            }
//        });
//        this.loadData();  //加载初始数据
//    }
//
//    /**  加载数据 */
//    public void loadData(){
//        //加载当前用户数据
//        if(null != DataBuffer.currentUser){
//            currentUserLbl.setIcon(
//                    new ImageIcon("images/" + DataBuffer.currentUser.getHead() + ".png"));
//            currentUserLbl.setText(DataBuffer.currentUser.getNickname()
//                    + "(" + DataBuffer.currentUser.getId() + ")");
//        }


//
//    /** 发送振动 */
//    public void sendShakeMsg(){
//        User selectedUser = (User)onlineList.getSelectedValue();
//        if(null != selectedUser){
//            if(DataBuffer.currentUser.getId() == selectedUser.getId()){
//                JOptionPane.showMessageDialog(ChatFrame.this, "不能给自己发送振动!",
//                        "不能发送", JOptionPane.ERROR_MESSAGE);
//            }else{
//                Message msg = new Message();
//                msg.setFromUser(DataBuffer.currentUser);
//                msg.setToUser(selectedUser);
//                msg.setSendTime(new Date());
//
//                DateFormat df = new SimpleDateFormat("HH:mm:ss");
//                StringBuffer sb = new StringBuffer();
//                sb.append(" ").append(msg.getFromUser().getNickname())
//                        .append("(").append(msg.getFromUser().getId()).append(") ")
//                        .append(df.format(msg.getSendTime()))
//                        .append("\n  给").append(msg.getToUser().getNickname())
//                        .append("(").append(msg.getToUser().getId()).append(") ")
//                        .append("发送了一个窗口抖动\n");
//                msg.setMessage(sb.toString());
//
//                Request request = new Request();
//                request.setAction("shake");
//                request.setAttribute("msg", msg);
//                try {
//                    ClientUtil.sendTextRequest2(request);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//                ClientUtil.appendTxt2MsgListArea(msg.getMessage());
//                new JFrameShaker(ChatFrame.this).startShake();
//            }
//        }else{
//            JOptionPane.showMessageDialog(ChatFrame.this, "不能群发送振动!",
//                    "不能发送", JOptionPane.ERROR_MESSAGE); 9        }
//    }
//
//    /** 发送文本消息 */
//    public void sendTxtMsg(){
//        String content = sendArea.getText();
//        if ("".equals(content)) { //无内容
//            JOptionPane.showMessageDialog(ChatFrame.this, "不能发送空消息!",
//                    "不能发送", JOptionPane.ERROR_MESSAGE);
//        } else { //发送
//            User selectedUser = (User)onlineList.getSelectedValue();
//            if(null != selectedUser &&
//                    DataBuffer.currentUser.getId() == selectedUser.getId()){
//                JOptionPane.showMessageDialog(ChatFrame.this, "不能给自己发送消息!",
//                        "不能发送", JOptionPane.ERROR_MESSAGE);
//                return;
//            }
//
//            //如果设置了ToUser表示私聊，否则群聊
//            Message msg = new Message();
//            if(rybqBtn.isSelected()){  //私聊
//                if(null == selectedUser){
//                    JOptionPane.showMessageDialog(ChatFrame.this, "没有选择私聊对象!",
//                            "不能发送", JOptionPane.ERROR_MESSAGE);
//                    return;
//                }else{
//                    msg.setToUser(selectedUser);
//                }
//            }
//            msg.setFromUser(DataBuffer.currentUser);
//            msg.setSendTime(new Date());
//
//            DateFormat df = new SimpleDateFormat("HH:mm:ss");
//            StringBuffer sb = new StringBuffer();
//            sb.append(" ").append(df.format(msg.getSendTime())).append(" ")
//                    .append(msg.getFromUser().getNickname())
//                    .append("(").append(msg.getFromUser().getId()).append(") ");
//            if(!this.rybqBtn.isSelected()){//群聊
//                if(null == selectedUser){
//                    sb.append("对大家说");
//                }else{
//                    sb.append("对").append(selectedUser.getNickname())
//                            .append("(").append(selectedUser.getId()).append(")")
//                            .append("说");
//                }
//            }
//            sb.append("\n  ").append(content).append("\n");
//            msg.setMessage(sb.toString());
//
//            Request request = new Request();
//            request.setAction("chat");
//            request.setAttribute("msg", msg);
//            try {
//                ClientUtil.sendTextRequest2(request);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//
//            //JTextArea中按“Enter”时，清空内容并回到首行
//            InputMap inputMap = sendArea.getInputMap();
//            ActionMap actionMap = sendArea.getActionMap();
//            Object transferTextActionKey = "TRANSFER_TEXT";
//            inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0),transferTextActionKey);
//            actionMap.put(transferTextActionKey,new AbstractAction() {
//                private static final long serialVersionUID = 7041841945830590229L;
//                public void actionPerformed(ActionEvent e) {
//                    sendArea.setText("");
//                    sendArea.requestFocus();
//                }
//            });
//            sendArea.setText("");
//            ClientUtil.appendTxt2MsgListArea(msg.getMessage());
//        }
//    }
//
//    /** 发送文件 */
//    private void sendFile() {
//        User selectedUser = (User)onlineList.getSelectedValue();
//        if(null != selectedUser){
//            if(DataBuffer.currentUser.getId() == selectedUser.getId()){
//                JOptionPane.showMessageDialog(ChatFrame.this, "不能给自己发送文件!",
//                        "不能发送", JOptionPane.ERROR_MESSAGE);
//            }else{
//                JFileChooser jfc = new JFileChooser();
//                if (jfc.showOpenDialog(ChatFrame.this) == JFileChooser.APPROVE_OPTION) {
//                    File file = jfc.getSelectedFile();
//                    sendFile = new FileInfo();
//                    sendFile.setFromUser(DataBuffer.currentUser);
//                    sendFile.setToUser(selectedUser);
//                    try {
//                        sendFile.setSrcName(file.getCanonicalPath());
//                    } catch (IOException e1) {
//                        e1.printStackTrace();
//                    }
//                    sendFile.setSendTime(new Date());
//
//                    Request request = new Request();
//                    request.setAction("toSendFile");
//                    request.setAttribute("file", sendFile);
//                    try {
//                        ClientUtil.sendTextRequest2(request);
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//
//                    ClientUtil.appendTxt2MsgListArea("【文件消息】向 "
//                            + selectedUser.getNickname() + "("
//                            + selectedUser.getId() + ") 发送文件 ["
//                            + file.getName() + "]，等待对方接收...\n");
//                }
//            }
//        }else{
//            JOptionPane.showMessageDialog(ChatFrame.this, "不能给所有在线用户发送文件!",
//                    "不能发送", JOptionPane.ERROR_MESSAGE);
//        }
//    }
//
//    /** 关闭客户端 */
//    private void logout() {
//        int select = JOptionPane.showConfirmDialog(ChatFrame.this,
//                "确定退出吗？\n\n退出程序将中断与服务器的连接!", "退出聊天室",
//                JOptionPane.YES_NO_OPTION);
//        if (select == JOptionPane.YES_OPTION) {
//            Request req = new Request();
//            req.setAction("exit");
//            req.setAttribute("user", DataBuffer.currentUser);
//            try {
//                ClientUtil.sendTextRequest(req);
//            } catch (IOException ex) {
//                ex.printStackTrace();
//            }finally{
//                System.exit(0);
//            }
//        }else{
//            this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
//        }
    }
}